//
//  NSObject+Request.m
//  TooToo
//
//  Created by liuning on 15/12/29.
//  Copyright © 2015年 MoHao. All rights reserved.
//

#import "NSObject+Request.h"
#import "AFNetworking.h"
#import "DeviceManager.h"
#import "NoticePopHelper.h"

@interface NSObject ()

@end

@implementation NSObject (Request)


-(void)setHeaderInfo:(AFHTTPRequestSerializer*)requestSerializer
{
    
    NSString *localeLanguageCode = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    [requestSerializer setValue:[[DeviceManager sharedInstance] getDeviceId] forHTTPHeaderField:@"uuid"];
    [requestSerializer setValue:@"iOS" forHTTPHeaderField:@"platform"];
    [requestSerializer setValue:appVersion forHTTPHeaderField:@"versioncode"];
    [requestSerializer setValue:localeLanguageCode forHTTPHeaderField:@"lang"];
    
    //登录信息
    if ([UserInfoManager sharedManager].isLogin) {
        [requestSerializer setValue:[UserInfoManager sharedManager].userId forHTTPHeaderField:@"uid"];
        [requestSerializer setValue:[UserInfoManager sharedManager].token forHTTPHeaderField:@"token"];
    }
}

-(void)responseAdapter:(NSDictionary *)dict code:(NSInteger)code
{
    if(![SafeGetStringValue([dict objectForKey:@"success"]) isEqualToString:@"1"])
    {
        //业务逻辑错误
        [self requestLogicError:[dict objectForKey:@"data"] code:code];
    }
    else
    {
        //返回成功
        [self requestSuccess:[dict objectForKey:@"data"] code:code];
    }
}


//Get请求
-(void)get:(NSString*)urlString code:(NSInteger)code
{
    __weak NSObject * weakSelf = self;
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    //请求头
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    [self setHeaderInfo:requestSerializer];
    session.requestSerializer = requestSerializer;
    
    //支持所有格式
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [session setResponseSerializer:responseSerializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    
    //防止请求中文时候不支持
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [session GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [weakSelf responseAdapter:responseObject code:code];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [NoticePopHelper showNoticeText:@"网络不稳定"];

        [weakSelf requestFailure:error code:code];
        
    }];

}


//post请求
-(void)post:(NSString*)urlString param:(NSDictionary*)param code:(NSInteger)code
{
    NSLog(@"url=====%@  post==%@",urlString,param);
    __weak NSObject * weakSelf = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //请求头
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    [self setHeaderInfo:requestSerializer];
    manager.requestSerializer = requestSerializer;
    
    //支持所有格式
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [manager setResponseSerializer:responseSerializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];

    //防止请求中文时候不支持
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [manager POST:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [weakSelf responseAdapter:responseObject code:code];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [NoticePopHelper showNoticeText:@"网络不稳定"];

        [weakSelf requestFailure:error code:code];
        
    }];
}

-(void)getDataByUrl:(NSString *)urlString success:(void(^)(NSData * data))success failure:(void(^)(NSError *error))failure
{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //防止请求中文时候不支持
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [session GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //返回成功
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
    }];
}

-(void)getDataByUrl:(NSString *)urlString code:(NSInteger)code
{
    __weak NSObject * weakSelf = self;
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    //无条件的信任服务器上的证书
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    // 客户端是否信任非法证书
    securityPolicy.allowInvalidCertificates = YES;
    // 是否在证书域字段中验证域名
    securityPolicy.validatesDomainName = NO;
    session.securityPolicy = securityPolicy;

    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    [self setHeaderInfo:requestSerializer];
    session.requestSerializer = requestSerializer;
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (EtherAllTokenAPI_URL_Code == code) {
        // 设置超时时间
        [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        session.requestSerializer.timeoutInterval = 20.f;
        [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    }
    
    
    
    //防止请求中文时候不支持
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [session GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"~~~AFN请求数据成功");
        
        //返回成功
        [weakSelf requestData:responseObject code:code];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"~~~AFN请求数据失败 %@",error);
        [weakSelf requestFailure:error code:code];
        
    }];
}

-(void)postDataByUrl:(NSString *)urlString param:(NSDictionary*)param code:(NSInteger)code
{
    __weak NSObject * weakSelf = self;
    
    NSMutableDictionary *postData = [[NSMutableDictionary alloc] initWithDictionary:param];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //防止请求中文时候不支持
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [session POST:urlString parameters:postData progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"~~~AFN请求数据成功");
        
        //返回成功
        [weakSelf requestData:responseObject code:code];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
//        NSLog(@"~~~AFN请求数据失败 %@",error);
        [weakSelf requestFailure:error code:code];
    }];
    
}


//请求成功回调
-(void)requestSuccess:(id)data code:(NSInteger)code
{
}

//业务错误
-(void)requestLogicError:(id)data code:(NSInteger)code
{
    NSString *info =SafeGetStringValue([data objectForKey:@"msg"]);
    [NoticePopHelper showNoticeText:info];
}

//请求失败回调
-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
}

//Data请求成功回调
-(void)requestData:(NSData *)data code:(NSInteger)code
{
    
}
@end
